#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
  int fd[2] = {0};
  if(pipe(fd)<0)
  {//使用pipe创建匿名管道
    perror("pipe");
    return 1;
  }
  //创建子进程
  pid_t id = fork();
  if(id == 0)
  {
    close(fd[0]);//子进程关闭读端
    //子进程写入数据
    const char* msg = "hello father,I am child...";
    int count = 10;
    while(count--)
    {
      write(fd[1],msg,strlen(msg));
      sleep(1);  //写端进程不写，读端进程一直读，那么此时会因为管道里面没有数据可读，对应的读端进程会被挂起，直到管道里面有数据后，读端进程才会被唤醒。
    }
    close(fd[1]);//写入完毕，关闭文件
    exit(0);
  }
  //father
  close(fd[1]);//父进程关闭写端
  //父进程读取数据
  char buffer[64];
  while(1)
  {
    ssize_t s = read(fd[0],buffer,sizeof(buffer));
    if(s>0)
    {
      buffer[s] = '\0';
      printf("child send to father:%s\n",buffer);
    }
    else if(s==0)
    {
      printf("read file end!!\n");
      break;
    }
    else
    {
      printf("read filed!!\n");
      break;
    }


  }

  close(fd[0]);
  waitpid(id,NULL,0);//等待子进程
  return 0;
}
